package co.sanduche.teach.service;

import java.io.File;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.util.Log;
import co.sanduche.models.Models.Photo;
import co.sanduche.services.EndPoints;
import co.sanduche.teach.TeachApp;
import co.sanduche.teach.gallery.GalleryDBOpenHelper;
import co.sanduche.teach.gallery.ImageItem;
import co.sanduche.teach.service.ServiceManager.ServiceBinder;
import co.sanduche.util.EPFuture;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;

public class UploadPhotoTask extends TaskExecutor {

	protected long id;
	protected GalleryDBOpenHelper dbHelper;
	protected AmazonS3Client s3Client = new AmazonS3Client(
			new BasicAWSCredentials(TeachApp.AWSAccessKeyId,
					TeachApp.AWSSecretKey));
	private ServiceBinder binder;

	public UploadPhotoTask() {
	}

	@Override
	public void init(Context context, ServiceBinder binder, Task t) {
		this.id = t.getEntityId();
		dbHelper = new GalleryDBOpenHelper(context);
		this.binder = binder;

	}

	public void execute() throws Exception {
		ImageItem ii = dbHelper.get(id);
		upload(ii);
	}

	private void upload(final ImageItem ii) throws Exception {
		try {
			Log.v(getClass().getSimpleName(), "Uploading Photo " + ii.getPath());
			ii.setState(System.currentTimeMillis());
			dbHelper.update(ii);
			binder.showUploading(true, ii);

			if (ii.getUrl() == null) {
				String s3Bucket = TeachApp.S3_BUCKET;
				String imageName = "upload_" + System.currentTimeMillis()
						+ ".jpg";
				String url = "https://s3.amazonaws.com/" + s3Bucket + "/"
						+ imageName;
				File file = new File(ii.getPath());

				PutObjectRequest por = new PutObjectRequest(s3Bucket,
						imageName, file)
						.withCannedAcl(CannedAccessControlList.PublicRead);
				s3Client.putObject(por);
				ii.setUrl(url);
				dbHelper.update(ii);
			}
			// binder.showMessage("Imagen cargada a la nube");
			final String url = ii.getUrl();
			Photo body = new Photo();
			body.setUrl(url);
			body.setDescription(ii.getMessage());

			EPFuture<Photo> future = EPFuture.newFuture();
			EndPoints.PostsEP.uploadPhoto(body, future);
			Photo p = future.get(10, TimeUnit.SECONDS);
			ii.setServerId(p.getId());
			ii.setState(1);
			dbHelper.update(ii);
			binder.showUploading(false, ii);

		} catch (Exception e) {
			ii.setState(0);
			dbHelper.update(ii);
			binder.showUploading(false, ii);

			Log.i(getClass().getSimpleName(), "Error:" + e.getMessage());
			throw e;
		}
	}
}
